<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="项目编号" prop="projectNum">
            <el-select :disabled="isEditMode"
                v-model="dataForm.projectNum"
                placeholder="请选择项目编号"
                class="label_len">
              <el-option
                  v-for="item in projectList"
                  :key="item.prProjectNumber"
                  :label="item.prProjectNumber + ' ' + item.prProjectName"
                  :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
    <el-form-item label="测定地点" prop="testLocation">
      <el-input v-model="dataForm.testLocation" placeholder="测定地点"></el-input>
    </el-form-item>
    <el-form-item label="测定日期" prop="testDate">
      <el-date-picker
        v-model="dataForm.testDate"
        type="date" format="yyyy-MM-dd" @change="handleDateChange"
        placeholder="选择测定日期">
      </el-date-picker>
    </el-form-item>
    <el-table :data="gaugingPoints" style="width: 100%">
        <el-table-column prop="index" label="测点" width="150">
          <template slot-scope="scope">
            {{ scope.$index + 1 }} <!-- 显示测点序号 -->
          </template>
        </el-table-column>
        <el-table-column prop="left" label="左值" width="300">
          <template slot-scope="scope">
            <el-input type="number" v-model.number="scope.row.left" @change="calculateStatistics"  placeholder="输入左值"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="right" label="右值" width="300">
          <template slot-scope="scope">
            <el-input type="number" v-model.number="scope.row.right" @change="calculateStatistics"  placeholder="输入右值"></el-input>
          </template>
        </el-table-column>
      </el-table>
    <el-row gutter={20}>
        <el-col :span="12">
          <el-form-item label="平均值">
            <el-input v-model="dataForm.avg" placeholder="计算值" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="校验值">
            <el-input v-model="dataForm.avgValue" placeholder="输入校验值"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    <el-form-item label="标准差" prop="sd">
      <el-input v-model="dataForm.sd" placeholder="标准差"></el-input>
    </el-form-item>
    <el-form-item label="变异系数" prop="cv">
      <el-input v-model="dataForm.cv" placeholder="变异系数"></el-input>
    </el-form-item>
    <el-row gutter={20}>
        <el-col :span="12">
          <el-form-item label="稳定系数">
            <el-input v-model="dataForm.sc" placeholder="计算值" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="校验值">
            <el-input v-model="dataForm.verificationValue" placeholder="输入校验值"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          projectNum: '',
          testLocation: '',
          testDate: '',
          gaugingPoint: '',
          avg: '',
          sd: '',
          cv: '',
          sc: '',
          inspectorName: '',
          recordName: '',
          checkerName: ''
        },
        projectList: [],
        isEditMode: false,
        dataRule: {
          projectNum: [
            { required: true, message: '项目编号不能为空', trigger: 'blur' }
          ],
          testLocation: [
            { required: true, message: '测定地点不能为空', trigger: 'blur' }
          ],
          testDate: [
            { required: true, message: '测定日期不能为空', trigger: 'blur' }
          ],
          avg: [
            { required: true, message: '平均值不能为空', trigger: 'blur' }
          ],
          sd: [
            { required: true, message: '标准差不能为空', trigger: 'blur' }
          ],
          cv: [
            { required: true, message: '变异系数不能为空', trigger: 'blur' }
          ],
          sc: [
            { required: true, message: '稳定系数不能为空', trigger: 'blur' }
          ],
          inspectorName: [
            { required: true, message: '检测人姓名不能为空', trigger: 'blur' }
          ],
          recordName: [
            { required: true, message: '记录人姓名不能为空', trigger: 'blur' }
          ],
          checkerName: [
            { required: true, message: '校核人姓名不能为空', trigger: 'blur' }
          ]
        },
        gaugingPoints: Array.from({ length: 11 }, () => ({ left: null, right: null })) // 初始化11个测点
      }
    },
    mounted (){
    this.getprojectList()
    },
    methods: {
      //获取项目列表
      getprojectList() {
        this.$http({
          url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
          method: 'post',
          data: this.$http.adornData({
          })
        }).then((data) => {
          if (data && data.code === 0) {
            //console.log(data.productList)
            this.projectList = data.productList
          } else {
            this.$message.error(data.msg)
          }
        })
      },

    generateJsonString() {
      const jsonObject = {};
      this.gaugingPoints.forEach((point, index) => {
        jsonObject[index] = {
          left: point.left,
          right: point.right
        };
      });
      return JSON.stringify(jsonObject);
    },
    convertJsonStringToArray(jsonString) {
      const jsonObject = JSON.parse(jsonString); // 解析 JSON 字符串
      const resultArray = []; // 创建一个空数组以存储结果

      for (const id in jsonObject) {
        const item = {
          left: jsonObject[id].left,
          right: jsonObject[id].right
        };
        resultArray.push(item); // 将解析出的项目添加到结果数组中
      }

      return resultArray; // 返回转换后的数组
    },
    calculateStatistics() {
      // 从 gaugingPoints 中提取有效的左值和右值
      const leftValues = this.gaugingPoints.map(point => point.left).filter(value => value !== null);
      const rightValues = this.gaugingPoints.map(point => point.right).filter(value => value !== null);
      
      // 合并左值和右值
      const allValues = [...leftValues, ...rightValues];
      
      // 计算平均值
      const avg = allValues.length ? (allValues.reduce((sum, value) => sum + value, 0) / allValues.length) : 0;

      // 计算标准差
      const sd = this.calculateStandardDeviation(allValues, avg);

      // 计算变异系数
      const cv = avg !== 0 ? (sd / avg) * 100 : 0;

      // 计算稳定系数（根据需要定义稳定系数的计算方式）
      const sc = allValues.length ? Math.abs(allValues[0] - avg) : 0; // 示例：取第一个值与平均值的差

      // 更新统计值，四舍五入到小数点后两位
      this.dataForm.avg = Math.round(avg * 100) / 100; // 计算平均值，保留两位小数
      this.dataForm.sd = Math.round(sd * 100) / 100;   // 计算标准差，保留两位小数
      this.dataForm.cv = Math.round(cv * 100) / 100;   // 计算变异系数，保留两位小数
      this.dataForm.sc = Math.round(sc * 100) / 100;   // 计算稳定系数，保留两位小数
    },


    calculateStandardDeviation(values, mean) {
      if (values.length === 0) return 0;
      const variance = values.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / values.length;
      return Math.sqrt(variance);
    },
    handleDateChange(value) {
        if (value) {
          // 将选择的日期转换为 UTC 字符串
          const date = new Date(value);
          const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
          this.dataForm.testDate = utcDate.toISOString();
        }
      },
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.isEditMode = false;
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/deepstabilityrecord/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.isEditMode =true;
                this.dataForm.projectNum = data.deepStabilityRecord.projectNum
                this.dataForm.testLocation = data.deepStabilityRecord.testLocation
                this.dataForm.testDate = data.deepStabilityRecord.testDate
                this.gaugingPoints = this.convertJsonStringToArray(data.deepStabilityRecord.gaugingPoint);
                this.dataForm.avg = data.deepStabilityRecord.avg
                this.dataForm.sd = data.deepStabilityRecord.sd
                this.dataForm.cv = data.deepStabilityRecord.cv
                this.dataForm.sc = data.deepStabilityRecord.sc
                this.dataForm.inspectorName = data.deepStabilityRecord.inspectorName
                this.dataForm.recordName = data.deepStabilityRecord.recordName
                this.dataForm.checkerName = data.deepStabilityRecord.checkerName
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const gaugingPoint = this.generateJsonString();
             // 检查校验值是否存在
              const stableCoefficient = this.dataForm.verificationValue !== null && this.dataForm.verificationValue !== ''
                ? this.dataForm.verificationValue // 使用校验值
                : this.dataForm.sc; // 否则使用计算值
              const avg = this.dataForm.avg !== null && this.dataForm.avgValue !== ''
                ? this.dataForm.avgValue // 使用校验值
                : this.dataForm.avg; // 否则使用计算值
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/deepstabilityrecord/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'projectNum': this.dataForm.projectNum,
                'testLocation': this.dataForm.testLocation,
                'testDate':new Date(this.dataForm.testDate).toISOString().split('T')[0],
                'gaugingPoint': gaugingPoint,
                'avg': avg,
                'sd': this.dataForm.sd,
                'cv': this.dataForm.cv,
                'sc': stableCoefficient,
                'inspectorName': this.dataForm.inspectorName,
                'recordName': this.dataForm.recordName,
                'checkerName': this.dataForm.checkerName
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
